package com.vb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vb.entity.CableShop;
import com.vb.entity.SearchResult;
import com.vb.mapper.CableShopMapper;
import com.vb.service.CableShopService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import static com.vb.utils.SearchUtil.search;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class CableShopServiceImpl extends ServiceImpl<CableShopMapper, CableShop> implements CableShopService {
    @Override
    public Map<String, Object> getSearchShop(String base64String) throws IOException {
        List<SearchResult> search = search(base64String);
        List<SearchResult> fiveResult = search;
        if (search.size()>5){
            fiveResult = search.subList(0, 5);
        }
        System.out.println(fiveResult);
        List<String> pathList = fiveResult.stream().map(SearchResult::getPath)
                .collect(Collectors.toList());
        QueryWrapper<CableShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("shop_places",pathList);
        List<CableShop> cableShops = baseMapper.selectList(queryWrapper);
        Map<String, Object> res = new HashMap<>();
        ArrayList<CableShop> cableShopsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cableShops)){
            cableShops.forEach(e->{
                if (cableShopsList.size() <= 5){
                    cableShopsList.add(e);
                }
            });

            // 根据集合search中的path顺序重新排序集合cableShopsList
            cableShopsList.sort((shop1, shop2) -> {
                int index1 = getIndex(search, shop1.getShopPlaces());
                int index2 = getIndex(search, shop2.getShopPlaces());
                return Integer.compare(index1, index2);
            });

            res.put("list",cableShopsList);
            res.put("msg","success");
        }else {
            res.put("msg","暂无数据");
        }
        return res;
    }

    // 辅助方法：根据path获取在集合search中的索引
    private static int getIndex(List<SearchResult> search, String path) {
        for (int i = 0; i < search.size(); i++) {
            if (search.get(i).getPath().equals(path)) {
                return i;
            }
        }
        return -1;
    }
}
